package com.example.riceexambackend.controller;

import com.example.riceexambackend.common.errorcode.ControllerErrorCodeConstants;
import com.example.riceexambackend.common.exception.ControllerException;
import com.example.riceexambackend.common.pojo.CommonResult;
import com.example.riceexambackend.common.utils.JacksonUtil;
import com.example.riceexambackend.controller.param.user.UserCurrentParam;
import com.example.riceexambackend.controller.param.user.UserLoginPasswordParam;
import com.example.riceexambackend.controller.param.user.UserRegisterParam;
import com.example.riceexambackend.controller.result.user.UserCurrentResult;
import com.example.riceexambackend.controller.result.user.UserLoginResult;
import com.example.riceexambackend.controller.result.user.UserRegisterResult;
import com.example.riceexambackend.service.UserService;
import com.example.riceexambackend.service.VerificationCodeService;
import com.example.riceexambackend.service.dto.user.UserCurrentDTO;
import com.example.riceexambackend.service.dto.user.UserLoginDTO;
import com.example.riceexambackend.service.dto.user.UserRegisterDTO;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private VerificationCodeService verificationCodeService;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 获取当前登录用户
     * @param param
     * @return
     */
    @PostMapping("/current")
    public CommonResult<UserCurrentResult> getCurrentUser(@Validated @RequestBody UserCurrentParam param) {
        // 日志打印
        logger.info("UserController getCurrentUser:{}", JacksonUtil.writeValueAsString(param));
        // 调用获取当前登录业务逻辑
        UserCurrentDTO userCurrentDTO = userService.getCurrentUser(param);
        UserCurrentResult result = convertToUserCurrentResult(userCurrentDTO);
        return CommonResult.success(result);
    }

    private UserCurrentResult convertToUserCurrentResult(UserCurrentDTO userCurrentDTO) {
        if (userCurrentDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.USER_CURRENT_ERROR);
        }
        UserCurrentResult result = new UserCurrentResult();
        result.setUserName(userCurrentDTO.getUserName());
        result.setUserAccount(userCurrentDTO.getUserAccount());
        result.setUserEmail(userCurrentDTO.getUserEmail());
        result.setUserRole(userCurrentDTO.getUserRole());
        result.setUserPhone(userCurrentDTO.getUserPhone());
        return result;
    }

    @PostMapping("/register")
    public CommonResult<UserRegisterResult> register(@Validated @RequestBody UserRegisterParam param) {
        // 日志打印
        logger.info("UserController register:{}", JacksonUtil.writeValueAsString(param));
        // 调用用户注册业务逻辑
        UserRegisterDTO userRegisterDTO = userService.register(param);
        UserRegisterResult result = convertToUserRegisterResult(userRegisterDTO);
        return CommonResult.success(result);
    }

//    /**
//     * 验证码登录
//     * @param param 登录参数
//     * @return 登录凭证
//     */
//    @PostMapping("/login/code")
//    public CommonResult<UserLoginResult> loginByVerifyCode(@RequestBody UserLoginVerifyCodeParam param) {
//        // 日志信息
//        logger.info("UserController loginByVerifyCode:{}", param);
//        // 调用登录业务逻辑
//        UserLoginDTO userLoginDTO = userService.login(param);
//        // 转换成result
//        UserLoginResult userLoginResult = convertToUserLoginResult(userLoginDTO);
//        return CommonResult.success(userLoginResult);
//    }
//
    /**
     * 密码登录
     * @param param 登录参数
     * @return 登录凭证
     */
    @PostMapping("/login/password")
    public CommonResult<UserLoginResult> loginByPassword(@RequestBody UserLoginPasswordParam param) {
        // 日志信息
        logger.info("UserController loginByPassword:{}", param);
        // 调用登录业务逻辑
        UserLoginDTO userLoginDTO = userService.loginByPassword(param);
        // 转换成result
        UserLoginResult userLoginResult = convertToUserLoginResult(userLoginDTO);
        return CommonResult.success(userLoginResult);
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        UserLoginResult userLoginResult = new UserLoginResult();
        if (userLoginDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.USER_LOGIN_ERROR);
        }
        userLoginResult.setToken(userLoginDTO.getToken());
        userLoginResult.setUserRole(userLoginDTO.getUserRole());
        return userLoginResult;
    }

    @GetMapping("/captcha/send")
    public CommonResult<Boolean> sendCaptchaCode(String phoneNumber) {
        // 日志打印
        logger.info("UserController sendCaptchaCode:{}", phoneNumber);
        if (!StringUtils.hasText(phoneNumber)) {
            throw new ControllerException(ControllerErrorCodeConstants.USER_VERIFY_CODE_PHONE_ERROR);
        }
        // 发送验证码
        verificationCodeService.sendVerifyCode(phoneNumber);
        return CommonResult.success(Boolean.TRUE);
    }

    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        if (userRegisterDTO == null ||
            userRegisterDTO.getId() <= 0) {
            // 抛出异常
            throw new ControllerException(ControllerErrorCodeConstants.USER_REGISTER_ERROR);
        }
        UserRegisterResult userRegisterResult = new UserRegisterResult();
        userRegisterResult.setUserId(userRegisterDTO.getId());
        return userRegisterResult;
    }
}
